package com.example.myapplication.realtime

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.example.myapplication.MainActivity
import com.example.myapplication.R
import com.example.myapplication.UserSession
import com.example.myapplication.UserType
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collectLatest

/**
 * 实时通信服务 - 在后台保持WebSocket连接
 */
class RealtimeService : Service() {

    companion object {
        private const val TAG = "RealtimeService"
        private const val NOTIFICATION_ID = 102
        private const val CHANNEL_ID = "realtime_service_channel"
        private const val CHANNEL_NAME = "实时通信服务"
        fun startService(context: android.content.Context) {
            val intent = Intent(context, RealtimeService::class.java)
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
        fun stopService(context: android.content.Context) {
            val intent = Intent(context, RealtimeService::class.java)
            context.stopService(intent)
        }
        const val ACTION_CONNECT = "com.example.myapplication.CONNECT_WEBSOCKET"
        const val ACTION_DISCONNECT = "com.example.myapplication.DISCONNECT_WEBSOCKET"
        const val ACTION_REFRESH_DATA = "com.example.myapplication.REFRESH_DATA"
        const val ACTION_SYNC_DATA = "com.example.myapplication.SYNC_DATA"
        const val ACTION_UPDATE_USER_STATUS = "com.example.myapplication.UPDATE_USER_STATUS"
    }

    private val binder = LocalBinder()
    private val webSocketManager by lazy { WebSocketManager.getInstance(this) }
    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    inner class LocalBinder : Binder() {
        fun getService(): RealtimeService = this@RealtimeService
    }

    override fun onCreate() {
        super.onCreate()
        try {
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification("实时通信服务运行中..."))
        setupWebSocketListener()
        startWebSocketConnection()
            Log.d(TAG, "实时通信服务创建成功")
        } catch (e: Exception) {
            Log.e(TAG, "实时通信服务创建失败", e)
            // 即使失败也要确保服务能启动
            startForeground(NOTIFICATION_ID, createNotification("实时通信服务启动中..."))
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "实时通信服务启动")
        when (intent?.action) {
            ACTION_CONNECT -> startWebSocketConnection()
            ACTION_DISCONNECT -> stopWebSocketConnection()
        }
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }

    override fun onDestroy() {
        super.onDestroy()
        stopWebSocketConnection()
        serviceScope.cancel()
        Log.d(TAG, "实时通信服务停止")
    }

    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "实时通信服务通知"
                setShowBadge(false)
            }
            val notificationManager = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                getSystemService(NotificationManager::class.java)
            } else {
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            }
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建通知
     */
    private fun createNotification(content: String): Notification {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("患者管理系统")
            .setContentText(content)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setAutoCancel(false)
            .build()
    }

    /**
     * 更新通知
     */
    private fun updateNotification(status: WebSocketManager.ConnectionStatus) {
        val content = when (status) {
            WebSocketManager.ConnectionStatus.DISCONNECTED -> "连接断开，尝试重连..."
            WebSocketManager.ConnectionStatus.CONNECTING -> "正在连接..."
            WebSocketManager.ConnectionStatus.CONNECTED -> "实时通信已连接"
            WebSocketManager.ConnectionStatus.ERROR -> "连接出错，正在重试..."
        }
        val notification = createNotification(content)
        val notificationManager = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            getSystemService(NotificationManager::class.java)
        } else {
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        }
        notificationManager.notify(NOTIFICATION_ID, notification)
    }

    /**
     * 设置WebSocket监听器
     */
    private fun setupWebSocketListener() {
        // 监听连接状态变化
        serviceScope.launch {
            webSocketManager.connectionStatus.collectLatest { status ->
                updateNotification(status)
                Log.d(TAG, "WebSocket状态变化: $status")
            }
        }
        // 监听消息
        serviceScope.launch {
            webSocketManager.lastMessage.collectLatest { message ->
                message?.let { handleRealtimeMessage(it) }
            }
        }
        // 添加消息监听器
        webSocketManager.addMessageListener(object : WebSocketManager.MessageListener {
            override fun onMessageReceived(message: WebSocketManager.RealtimeMessage) {
                handleRealtimeMessage(message)
            }
        })
    }

    /**
     * 处理实时消息
     */
    private fun handleRealtimeMessage(message: WebSocketManager.RealtimeMessage) {
        try {
            // 检查消息类型是否为null
            if (message.type == null) {
                Log.e(TAG, "收到无效消息，MessageType为null")
                return
            }
            
        when (message.type) {
            WebSocketManager.MessageType.PATIENT_REPORT -> {
                handlePatientReport(message.data as WebSocketManager.PatientReportData)
            }
            WebSocketManager.MessageType.NOTIFICATION -> {
                handleNotification(message.data as WebSocketManager.NotificationData)
            }
            WebSocketManager.MessageType.USER_REGISTER -> {
                handleUserRegister(message.data as WebSocketManager.UserRegisterData)
            }
            WebSocketManager.MessageType.DATA_SYNC -> {
                handleDataSync(message.data)
            }
            WebSocketManager.MessageType.USER_STATUS -> {
                handleUserStatus(message.data)
            }
            else -> {
                Log.d(TAG, "收到消息: ${message.type}")
            }
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理实时消息失败", e)
        }
    }

    /**
     * 处理患者上报消息
     */
    private fun handlePatientReport(data: WebSocketManager.PatientReportData) {
        Log.d(TAG, "收到患者上报: ${data.patientName} - ${data.reporterName}")
        // 发送本地通知
        sendLocalNotification(
            "新患者上报",
            "${data.reporterName} 上报了患者 ${data.patientName}",
            data.patientId.toInt()
        )
        // 刷新主界面数据
        sendBroadcast(Intent(ACTION_REFRESH_DATA))
    }

    /**
     * 处理通知消息
     */
    private fun handleNotification(data: WebSocketManager.NotificationData) {
        Log.d(TAG, "收到通知: ${data.title} - ${data.content}")
        // 检查是否发送给当前用户
        val currentUser = UserSession.currentUser
        if (currentUser != null) {
            val shouldShow = data.targetUserId == null || data.targetUserId == currentUser.id ||
                    data.targetDepartment == null || data.targetDepartment == currentUser.department
            if (shouldShow) {
                sendLocalNotification(data.title, data.content, 0)
            }
        }
    }
    
    /**
     * 处理用户注册消息
     */
    private fun handleUserRegister(data: WebSocketManager.UserRegisterData) {
        Log.d(TAG, "收到用户注册消息: ${data.realName} - ${data.department}")
        
        // 检查当前用户是否为管理员
        val currentUser = UserSession.currentUser
        if (currentUser != null && 
            (currentUser.userType == UserType.SUPER_ADMIN || 
             currentUser.userType == UserType.SUPER_SUPER_ADMIN)) {
            
            // 发送本地通知给管理员
            sendLocalNotification(
                "新用户注册",
                "${data.realName} (${data.username}) 申请注册，科室：${data.department}，类型：${data.userType}",
                data.userId.toInt()
            )
            
            // 刷新主界面数据
            sendBroadcast(Intent(ACTION_REFRESH_DATA))
        }
    }

    /**
     * 处理数据同步消息
     */
    private fun handleDataSync(data: Any?) {
        Log.d(TAG, "收到数据同步消息")
        // 触发数据同步
        sendBroadcast(Intent(ACTION_SYNC_DATA))
    }

    /**
     * 处理用户状态消息
     */
    private fun handleUserStatus(data: Any?) {
        Log.d(TAG, "收到用户状态消息")
        // 更新用户状态
        sendBroadcast(Intent(ACTION_UPDATE_USER_STATUS))
    }

    /**
     * 发送本地通知
     */
    private fun sendLocalNotification(title: String, content: String, id: Int) {
        val notificationManager = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            getSystemService(NotificationManager::class.java)
        } else {
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        }
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, id, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()
        notificationManager.notify(id, notification)
    }

    /**
     * 启动WebSocket连接
     */
    private fun startWebSocketConnection() {
        serviceScope.launch {
            try {
                webSocketManager.connect()
            } catch (e: Exception) {
                Log.e(TAG, "启动WebSocket连接失败", e)
            }
        }
    }

    /**
     * 停止WebSocket连接
     */
    private fun stopWebSocketConnection() {
        webSocketManager.disconnect()
    }

    /**
     * 发送患者上报消息
     */
    fun sendPatientReport(patientId: Long, patientName: String, reporterName: String, department: String) {
        webSocketManager.sendPatientReport(patientId, patientName, reporterName, department)
    }

    /**
     * 发送通知消息
     */
    fun sendNotification(title: String, content: String, targetUserId: Long? = null, targetDepartment: String? = null) {
        webSocketManager.sendNotification(title, content, targetUserId, targetDepartment)
    }

    /**
     * 获取连接状态
     */
    fun getConnectionStatus(): WebSocketManager.ConnectionStatus {
        return webSocketManager.connectionStatus.value
    }
} 